#include <string>
#include <iostream>
#include "../include/zmq.h"
#include "../include/zmq_utils.h"

int main() {
		// initialize the zmq context with a single IO thread
		void *ctx = nullptr;
		void *s = nullptr;
		zmq_msg_t msg;
		int rc = 0;
		ctx = zmq_init(1);
		if (!ctx) {
				printf("error in zmq_init: %s\n", zmq_strerror(errno));
				return -1;
		}
		s = zmq_socket(ctx, ZMQ_REP);
		if (!s) {
				printf("error in zmq_socket: %s\n", zmq_strerror(errno));
				return -1;
		}

		rc = zmq_bind(s, "tcp://127.0.0.1:8888");
		if (rc != 0) {
				printf("error in zmq_bind: %s\n", zmq_strerror(errno));
				return -1;
		}

		// set up some static data to send
		const std::string data{"world"};

		while (true) {
				rc = zmq_msg_init(&msg);
				if (rc < 0) {
						printf("error in zmq_msg_init: %s\n", zmq_strerror(errno));
						return -1;
				}
				rc = zmq_msg_recv(&msg, s, 0);
				if (rc < 0) {
						printf("error in zmq_recvmsg: %s\n", zmq_strerror(errno));
						return -1;
				}
				std::cout << "Received " << (char *) zmq_msg_data(&msg) << std::endl;
				zmq_msg_close(&msg);
				// send the request message
				rc = zmq_send(s, data.c_str(), data.size()+1, ZMQ_DONTWAIT);
				if (rc < 0) {
						printf("error in zmq_send: %s\n", zmq_strerror(errno));
						return -1;
				}
		}

		return 0;
}